<script setup lang="ts">
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query.js'

// 定义要素图层URL
const facilityLayerUrl = 'https://services.arcgis.com/cxicHGWOCJwYXasp/arcgis/rest/services/Facility/FeatureServer/0'

// 图表容器
const facilityChartContainer = ref<HTMLDivElement>()
const facilitytypeChart = ref<echarts.ECharts>()

// 统计数据
const facilitytypeData = ref<{name: string, value: number}[]>([])

// 初始化图表
const initCharts = () => {
  if (!facilityChartContainer.value) return

  // 设施类型分布图表
  facilitytypeChart.value = echarts.init(facilityChartContainer.value)
  facilitytypeChart.value.setOption({
    title: {
      text: '设施类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: facilitytypeData.value.map(item => item.name),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '设施数量',
        type: 'bar',
        data: facilitytypeData.value.map(item => item.value),
        itemStyle: {
          color: function(params: any) {
            // 为不同的柱子设置不同的颜色
            const colorList = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
            return colorList[params.dataIndex % colorList.length];
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

// 加载设施统计数据
const loadFacilityStats = async () => {
  try {
    const facilityLayer = new FeatureLayer({
      url: facilityLayerUrl,
      outFields: ['facilitytype']
    })

    const query = new Query({
      where: '1=1',
      outFields: ['facilitytype'],
      returnGeometry: false,
      groupByFieldsForStatistics: ['facilitytype'],
      outStatistics: [{
        statisticType: 'count',
        onStatisticField: 'objectid',
        outStatisticFieldName: 'count'
      }]
    })

    const results = await facilityLayer.queryFeatures(query)
    facilitytypeData.value = results.features.map(feature => ({
      name: feature.attributes.facilitytype || '未知类型',
      value: feature.attributes.count
    }))

    if (facilitytypeChart.value) {
      facilitytypeChart.value.setOption({
        xAxis: {
          data: facilitytypeData.value.map(item => item.name)
        },
        series: [{
          data: facilitytypeData.value.map(item => item.value)
        }]
      })
    }
  } catch (error) {
    ElMessage.error('加载设施统计数据失败')
    console.error(error)
  }
}



onMounted(() => {
  initCharts()
  loadFacilityStats()

  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    facilitytypeChart.value?.resize()
  })
})
</script>

<template>
  <div class="analysis-container">
    <h2 class="title">设施统计分析</h2>

    <div class="charts-wrapper">
      <div class="chart-container">
        <div class="chart" ref="facilityChartContainer" style="width: 100%; height: 400px;"></div>
      </div>
    </div>

    <div class="stats-grid">
      <div class="stat-card">
        <h3>设施总数</h3>
        <p class="stat-value">{{ facilitytypeData.reduce((sum, item) => sum + item.value, 0) }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.analysis-container {
  padding: 20px;
  height: auto;
  overflow-y: auto;
  position: relative;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  color: #409eff;
}

.charts-wrapper {
  display: flex;
  flex-direction: column;
  gap: 30px;
  margin-bottom: 30px;
}

.chart-container {
  width: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-top: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-card h3 {
  margin-top: 0;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin: 10px 0 0;
}
</style>
